import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.http.impl.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpEntity;
import java.util.ArrayList;
import java.util.List;
import java.io.InputStream;

@WebServlet(urlPatterns = {"/login/dgut"})
public class JsonServlet extends HttpServlet {
    // curl -v http://localhost:8080/test/json
    // curl -v -d "token=sai-dgut-kflajsdfjasdkfjal" http://localhost:8080/test/json

    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	String token = req.getParameter("token");
	String appid= "javaee";
	String appsecret="b3b52e43ccfd";
	String userip = req.getRemoteAddr();
	System.out.println(token);
	System.out.println(userip);

	CloseableHttpClient client = HttpClients.createDefault();
	HttpPost httpPost = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken");

	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("appid", appid));
	params.add(new BasicNameValuePair("appsecret", appsecret));
	params.add(new BasicNameValuePair("token", token));
	params.add(new BasicNameValuePair("userip", userip));

	httpPost.setEntity(new UrlEncodedFormEntity(params));

	HttpEntity entity = client.execute(httpPost).getEntity();
	String result = convertStreamToString(entity.getContent());
	System.out.println(result);

	Jsonb jsonb = JsonbBuilder.create();
	PostJson postjson  = jsonb.fromJson(result, PostJson.class);
	client.close();

	if(postjson.getError()== 0)
	{
	    client = HttpClients.createDefault();
	    httpPost = new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo");
	    params = new ArrayList<NameValuePair>();
	    params.add(new BasicNameValuePair("access_token", postjson.getAccess_token()));
	    params.add(new BasicNameValuePair("openid", postjson.getOpenid()));
	    httpPost.setEntity(new UrlEncodedFormEntity(params));

	    entity = client.execute(httpPost).getEntity();
	    result = convertStreamToString(entity.getContent());
	    System.out.println(result);

	    Person person  = jsonb.fromJson(result, Person.class);

	    String URL = getServletContext().getInitParameter("db.url");
	    String NAME = getServletContext().getInitParameter("db.user");
	    String PASSWORD = getServletContext().getInitParameter("db.password");

	    UserBean userBean = new UserBean(URL, NAME, PASSWORD, "123456", person.getUsername(), person.getName().substring(0,1), person.getName().substring(1,person.getName().length()),null);

	    (new DatabaseConnect(getServletContext())).updatesql(userBean);

	    Map<String, String> message = new LinkedHashMap<String, String>();
	    message.put("账号", person.getUsername());
	    message.put("姓", person.getName().substring(0,1));
	    message.put("名", person.getName().substring(1,person.getName().length()));
	    message.put("学院", person.getFaculty_title());
	    message.put("身份", person.getGroup());
	    HttpSession session = req.getSession(true);
	    session.setAttribute("Login", message);
	    session.setAttribute("dgutlogin","1");
	    resp.sendRedirect("http://localhost:8080/profile.jsp");

	}else resp.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");

    }
    private static String convertStreamToString(InputStream is) {

	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	StringBuilder sb = new StringBuilder();

	String line = null;
	try {
	    while ((line = reader.readLine()) != null) {
		sb.append(line + "\n");
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    try {
		is.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return sb.toString();
    }
}
